Web Api Request.CreateResponse HttpResponseMessage no intellisense VS2012 - c#

For some reason, Request.CreateResponse is now "red" in VS2012 and when I hover over the usage the IDE says
Cannot resolve symbol 'CreateResponse'
Here is the ApiController Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Filters;
using GOCApi.Attributes;
using GOCApi.Models;
using GOCApi.Models.Abstract;
using AttributeRouting;
using AttributeRouting.Web.Http;
namespace GOCApi.Controllers
{
[RoutePrefix("Courses")]
public class CoursesController : ApiController
{
private ICoursesRepository _coursesRepository { get; set; }
public CoursesController(ICoursesRepository coursesRepository)
{
_coursesRepository = coursesRepository;
}
[GET("{id}")]
public HttpResponseMessage Get(int id)
{
var course = _coursesRepository.GetSingle(id);
if (course == null)
return Request.CreateResponse(HttpStatusCode.NotFound, "Invalid ID");
return Request.CreateResponse(HttpStatusCode.OK, course);
}
}
}
Granted, the code does compile and works, it's just really annoying seeing all the "red" on my screen. Also, the intellisense doesn't work now when I type Request.CreateResponse. This also used to work, but I started developing other parts to my API and just came back to building controllers so I do not know what happened.
Any thoughts?

You need to add a reference to System.Net.Http.Formatting.dll. The CreateResponse extension method is defined there.

Because this extension method lives in System.Net.Http, you just need to include it in your usings statements.
using System.Net.Http;

You can use
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.Gone)
instead of
Request.CreateResponse(HttpStatusCode.Gone)

This is because you have to do:
namespace GOCApi.Controllers
{
[RoutePrefix("Courses")]
public class CoursesController : ApiController
{
private ICoursesRepository _coursesRepository { get; set; }
public CoursesController(ICoursesRepository coursesRepository)
{
_coursesRepository = coursesRepository;
}
[GET("{id}")]
public HttpResponseMessage Get(int id)
{
var course = _coursesRepository.GetSingle(id);
if (course == null){
return this.Request.CreateResponse(HttpStatusCode.NotFound, "Invalid ID");
}
return this.Request.CreateResponse(HttpStatusCode.OK, course);
}
}
}
Note the this.
In my case the compiler now gets it.
Saw the example here

Add a reference to System.Web.Http to the project. Then add
Using System.Web
to the top of the cs file.

This a known issue with VB.NET and Request.CreateResponse.
There is a workaround:
Missing request.CreateResponse in vb.net Webapi Projects

Related

Unable to access variables from another project

I am trying to automate API testing using c# (Restsharp). I have 2 projects in same solution. One project is a console app where I am trying to keep the methods, while the other one is a Unit Test Project where I plan on keeping the test cases.
I am able to access the methods from the BASE project by creating an object of the method, but unable to access the variables within that method to apply assertions. Any idea what am I missing?
(I am new to c#).
Method class in Base project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
namespace Base
{
public class Methods
{
public void GetMethod(long ID)
{
var client = new RestClient("getUrl");
var request = new RestRequest(Method.GET);
request.AddParameter("userId", ID);
IRestResponse response = client.Execute(request);
HttpStatusCode statusCode = response.StatusCode;
int nStatusCode = (int)statusCode;
}
}
}
UnitTest class in Test project
using System;
using System.Net;
using Base;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RestSharp;
namespace Tests
{
[TestClass]
public class UnitTests
{
[TestMethod]
public void StatusOK()
{
//Arrange, Act, Assert
var methods = new Methods();
methods.GetMethod(2330013)
Assert.IsTrue(nStatusCode.Equals(200));
}
}
}
UnitTest is unable to read nStatusCode variable, as well as response variable.
I have already added dependency between the projects.
Appreciate the help!!
One option to address the problem is to make GetMethod return the status code:
public int GetMethod(long ID)
{
...
int nStatusCode = (int)statusCode;
return nStatusCode;
}
Then the test can examine the return value.
var c = methods.GetMethod(2330013)
Assert.AreEqual(200, c);
PS. I recommend using Assert.AreEqual instead of Assert.IsTrue because in the case the code is not 200 the test failure output will contain the bad value. With IsTrue you will only know that it wasn't 200 but you won't know what it was.

How to return a JSON from WebAPI using http request?

I'm trying to implement a new web API. This API returns a JSON from HTTP-request.
So far I wrote very basic code, but the strange thing is that I get an error using XML template - and I have no idea what to do:
This is the call: http://localhost:55643/api/ShipmentsStatus/getShipmentsStatusJSON
The code is here:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace RunCom.WebAPI.Controllers
{
[Route("api/[controller]")]
public class ShipmentsStatusController : ApiController
{
// /api/ShipmentsStatus/getShipmentsStatusJSON
public ShipmentsStatusController()
{
int i = 0;
}
[HttpGet]
[Route("getShipmentsStatusJSON")]
public IEnumerable<String> Get()
{
test check = new test("1");
yield return JsonConvert.SerializeObject(check);
}
}
internal class test
{
string key;
public test(string k)
{
key = k;
}
}
}
The error I got is here:
<Error>
<Message>No HTTP resource was found that matches the request URI
'http://localhost:55643/api/ShipmentsStatus/getShipmentsJSON'.</Message>
<MessageDetail>No action was found on the controller 'ShipmentsStatus' that matches the request.</MessageDetail>
</Error>
What is wrong with my code?
Try to fix the route
[Route("~/api/ShipmentsStatus/GetShipmentsStatusJSON")]
public IEnumerable<string> Get()
{
return new List<string> {"1","2","3"};
}
You should use http://localhost:55643/api/ShipmentsStatus/getShipmentsStatusJSON or change [Route("getShipmentsStatusJSON")] to the appropriate API method name

Get JSON data out of Umbraco

I am a frontend developer so forgive my lack of ability to explain my issue.
I am trying to create some pages in an Umbraco project that display data using Vue.js. For this, I am trying to set up a custom API controller that will return the data I want, when called.
A simple example would be that I want to return all blog articles. Below is the code I have currently got:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Web;
using System.Web.Http;
using Umbraco.Web.WebApi;
using Umbraco.Web.PublishedContentModels;
using Newtonsoft.Json;
namespace Controllers.WebAPI.Qwerty
{
[Route("api/[controller]")]
public class PostsApiController : UmbracoApiController
{
[HttpGet]
public string Test()
{
return "qwerty";
}
}
}
I've read numerous articles and just can't seem to grasp what I need to do to query Umbraco for the data I want back?
I've tried adding
var content = Umbraco.TypedContent(1122);
And then returning that but I get errors stating:
(local variable) Umbraco.Core.Models.IPublishedContent content
Cannot implicitly convert type 'Umbraco.Core.Models.IPublishedContent' to 'string'
I have then tried serialising the var content but I get stuck with:
Self referencing loop detected for property 'FooterCtalink' with type
'Umbraco.Web.PublishedContentModels.Blog'. Path
'ContentSet[0].FeaturedProducts[0].Features[0].ContentSet[0]'.
Any help would be fantastic!
EDIT:
I have no edited the controller to be like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Web;
using Umbraco.Web.WebApi;
using Umbraco.Web.PublishedContentModels;
using Newtonsoft.Json;
using System.Web.Mvc;
using DTOs.PostDTO;
namespace Controllers.WebAPI.Qwerty
{
[Route("api/[controller]")]
public class PostsApiController : UmbracoApiController
{
[HttpGet]
public PostDTO Test()
{
// 1. Get content from umbraco
var content = Umbraco.TypedContent(1122);
// 2. Create instance of your own DTO
var myDTO = new PostDTO();
// 3. Pupulate your DTO
myDTO.Url = content.Url;
// 4. return it
return myDTO;
}
}
}
And created a DTO like so:
namespace DTOs.PostDTO
{
public class PostDTO
{
public string Url { get; set; }
}
}
However, when console logging my data after the ajax request, I only only getting 1122.
The issue is that you can't return a .NET Object in JSON that has the circular dependency.
To solve your problem, you can simply follow the below steps:
Create your own DTO & add required properties in that.
Fetch content from Umbraco API in C# & populate your custom DTO object.
Return that DTO from JsonResult.
Your code will look like below:
[Route("api/[controller]")]
public class PostsApiController : UmbracoApiController
{
[HttpGet]
public MyDTO Test()
{
// 1. Get content from umbraco
var content = Umbraco.TypedContent(1122);
// 2. Create instance of your own DTO
var myDTO = new MyDTO();
// 3. Pupulate your DTO
myDTO.SomeProperty = content.SomeProperty;
// 4. return it
return myDTO;
}
}
You are on the right track.
I think you need to return ActionResult instead of string.
Something like:
[HttpGet]
public ActionResult Test()
{
var content = Umbraco.TypedContent(1122);
return new JsonResult(content);
}
This should return the umbraco object as Json.

.Net Core MVC in VS Code "server.Models" missing reference

I've started with a fresh
dotnet new mvc -o .
dotnet restore
Opening Controllers/HomeController.cs I'm seeing an error regarding the reference to another .cs file in the same project...
The type or namespace name 'Models' does not exist
in the namespace 'server' (are you missing an assembly
reference?) [my-project]
I'm uncertain what the problem is... relatively new to .Net Core and using .Net via VS Code.
$ dotnet --version
2.1.201
~/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using server.Models;
namespace server.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
~/Models/ErrorViewModel.cs
using System;
namespace server.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
--
UPDATE: Seems to be an issue witht he omniview service and that I have VSCode opened to a parent directory of my server/ directory with the dotnet code.
I saw this error right after using dto (data transfer object) at the top of HomeController.cs, for example
using dto = webapplication.Models;
In my situation, the solution was to add the prefix dto. to ErrorViewModel like this:
public IActionResult Error()
{
return View(new dto.ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
I think that using server.Models; in your example is causing the problem too. Hope this helps to solve it.

Could not load type from another project in same assembly ASP.NET MVC

I have three asp.net mvc 5 projects in one solution. The solution is called Bank24 so the assembly too. Project Application_layer is main project. Also there is 2 more projects. There are BusinessLogic_layer where I'm working with database and Data layer where I'm creating database.
When I attempting to use class from BusinessLogic_layer in Application_layer I'm getting runtime server error -
Could not load type "BusinessLogic_layer.Services.DataService" from assembly "Bank24, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null"
Project Application_layer already has reference to BusinessLogic_layer. Directory that contains needed class already linked with Using directive. So I don't know why it doesen't loading.
Here is code of Controller MainController. I need to use desired class in method Register. It is linked with using BusinessLogic_layer.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Application_layer.Models;
using BusinessLogic_layer.Services;
namespace Application_layer.Controllers
{
[Authorize]
public class MainController : Controller
{
...
public UserManager<ApplicationUser> UserManager { get; private set; }
[HttpGet]
[AllowAnonymous]
//[ValidateAntiForgeryToken]
public void Register()
{
var user = new ApplicationUser() { UserName = "Admin" };
var result = UserManager.Create(user, "q1w2e3");
if (result.Succeeded)
{
DataService dataWorker = new DataService();
dataWorker.CreateUser("Admin", "Суренко Иван Васильевич", 0);
RedirectToAction("Login", "Authorization");
}
}
}
}
Here is code of DataService class which is in Services folder of another project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BusinessLogic_layer.Models;
using Data_layer.DataAccess;
using Data_layer.Models;
namespace BusinessLogic_layer.Services
{
public class DataService
{
...
public void CreateUser(string login, string name, byte role)
{
bool isEmployee = false;
if (role == 0)
isEmployee = true;
BankContext db = new BankContext();
db.Users.Add(new User() { Login = login, Name = name, Role = role, IsEmployee = isEmployee });
db.SaveChanges();
}
...
}
}
P.S. I have Visual Studio 2013
I've solved this problem. I started new project and begun testing. After a couple of hours I found several things. 1. Projects must be in different assemblys nevertheless they can be in one solution. I don't know why CLR could not load type when they are in same assembly. 2. It follows from 1 - all projects except main project must have empty project type.

Categories

Resources