I have the following Action:
[HttpPost]
public IHttpActionResult GetByUsername(string username)
{
return Ok(_userBusinessComponent.GetUserByUsername(username));
}
How can I send username to this action via Postman
I tried the followings, nothing response:
I change the signature of action as the following:
public IHttpActionResult GetByUsername([FromBody]string username)
This time username is always null !!!
As ibubi said, for the following web api action
[HttpPost]
public IHttpActionResult GetByUsername(string username)
{
return Ok(_userBusinessComponent.GetUserByUsername(username));
}
I have to use the following code:
http://localhost:51671/api/User/GetByUsername?username=Mohammad
Related
I want to take a some of data from users' input and then I want to transfer these between controllers.But this transfer must be done in the background for security. I don't want to send parameters on the URL.
I want to send the user object created in page1 controller to page2.
I used the model method for this, but I was not successful.
#Controller
public class DemoController {
...
..
.
#GetMapping("/page1")
public String page1(Model model) {
User user = new User();
user.setName("TestName");
user.setSurname("TestSurname");
user.setMail("xyzabc#gmail.com");
model.addAttribute("user", user);
return "redirect:/page2";
}
#GetMapping("/page2")
public String page2(#ModelAttribute("user") User user, Model model) {
System.out.println(user.toString());
return "page2";
}
.
..
...
}
How do I transfer objects?
There are 2 solutions for this question:
Solution 1: Store object in session
Code example:
#GetMapping("/page1")
public String page1(Model model, HttpSession session) {
...
session.setAttribute("user", user);
return "redirect:/page2";
}
#GetMapping("/page2")
public String page2(Model model, HttpSession session) {
User user = null;
if (session.getAttribute("user") != null) {
user = (User) session.getAttribute("user");
System.out.println(user.toString());
}
return "page2";
}
Solution 2: use forward instead of redirect
Code example:
#GetMapping("/page1")
public String page1(Model model) {
...
model.addAttribute("user", user);
return "forward:/page2";
}
you can use either :
session
or
2)forward:/page2 instead of redirect
I have an API that works fine locally and when I move it to the live environment it doesn't.
The main POST action on the affected controller returns:
NotFound
With a test GET action I get back:
"Message": "No HTTP resource was found that matches the request URI
Strangely, when I uploaded a testController with the same test action as used in the main controller I get a proper response from the API.
This is the test that works fine:
public class TestController : ApiController
{
[AllowAnonymous]
[HttpGet]
public HttpResponseMessage helloWorld()
{
return Request.CreateResponse(HttpStatusCode.OK, "HelloWorld!");
}
}
The controller which does not work:
public class DeviceController : ApiController
{
[AllowAnonymous]
[HttpGet]
public HttpResponseMessage helloWorld() // This returns: "No HTTP resource was found that matches the request URI 'http://api.mySite.com/api/Device/helloWorld'."
{
return Request.CreateResponse(HttpStatusCode.OK, "HelloWorld!");
}
[AllowAnonymous]
[HttpPost]
public HttpResponseMessage Login([FromBody] LoginObject loginObject) // This returns: "NotFound"
{
...
}
}
Here is the web config:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Try to add explicitly declare of route like by acrion
[Route("api/Device/helloWorld")]
[AllowAnonymous]
[HttpGet]
public HttpResponseMessage helloWorld()
or
[RoutePrefix("api/Device")]
public class DeviceController : ApiController
and then
[Route("helloWorld")]
[AllowAnonymous]
[HttpGet]
public HttpResponseMessage helloWorld()
For poor sap's like myself in the future: Ensure the methods on your controller are public.
I spent some time looking for the answer to this problem in .NET 7.0 after I had made a new project (which automatically created a WeatherForecastController).
It turns out that the project had also automatically created a file named proxy.conf.js. In the file, the context: setting was set to "/weatherforecast". I changed it to "/api" instead and then changed [Route("[controller]")] to [Route("api/[controller]")] in both controller files. The controllers worked fine after that.
I have implemented a web api controller using ASP.NET mvc 6 and I would like to return the result of the controller as json or xml, depending on the client's Accept header. For example, if the client sends a GET request with "Accept: application/xml", then the returned response should be xml. If the header is "Accept: application/json", then it should be json. At the moment the controller always returns json. Is there a way of configuring this? Note: this question is indeed a duplicate of How to return XML from an ASP.NET 5 MVC 6 controller action. However the solution provided there did not solve my problem. The accepted answer below worked for me.
The controller is given below and is the one provided by the ASP.NET 5 web api template:
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET: api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id:int}")]
public string Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
Thanks for your help!
I did the research for you, you may continue alone:
needed:
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.Core": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.Formatters.Xml": "6.0.0-rc1-final"
startup:
services.Configure<MvcOptions>(options =>
{
options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
});
go on from here
another
and antoher
I have setup very similar to breeze sample application which comes in sample nuget. This is the code of my api controller:
[JsonFormatter, ODataActionFilter]
public class WorkOrdersController : ApiController
{
readonly EFContextProvider<WorkOrdersContext> _contextProvider =
new EFContextProvider<WorkOrdersContext>();
public WorkOrdersController()
{
// I was thinking this may be the cause of the issue
this._contextProvider.Context.Configuration.ProxyCreationEnabled = false;
}
[HttpGet]
public string Metadata()
{
return _contextProvider.Metadata();
}
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle)
{
return _contextProvider.SaveChanges(saveBundle);
}
[HttpGet]
public IQueryable<WorkOrder> WorkOrders()
{
return _contextProvider.Context.WorkOrders;
}
}
The problem I'm having is when I try to perform query over WorkOrders action, I get 500 - Internal server error, and this is the payload of response:
{"$id":"1","$type":"System.Web.Http.HttpError, System.Web.Http","Message":"An error has occurred.","ExceptionMessage":"The action 'WorkOrders' on controller 'WorkOrders' with return type 'System.Collections.Generic.List`1[[WorkOrders.Domain.Models.WorkOrder, WorkOrders.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' cannot support querying. Ensure the type of the returned content is IEnumerable, IQueryable, or a generic form of either interface.","ExceptionType":"System.InvalidOperationException","StackTrace":" at System.Web.Http.QueryableAttribute.ValidateReturnType(Type responseContentType, HttpActionDescriptor actionDescriptor)\r\n at System.Web.Http.QueryableAttribute.OnActionExecuted(HttpActionExecutedContext actionExecutedContext)\r\n at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEnd(ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action`1 beginTrace, Action execute, Action`1 endTrace, Action`1 errorTrace)\r\n at System.Web.Http.Tracing.Tracers.ActionFilterAttributeTracer.OnActionExecuted(HttpActionExecutedContext actionExecutedContext)\r\n at System.Web.Http.Filters.ActionFilterAttribute.<>c__DisplayClass2.<System.Web.Http.Filters.IActionFilter.ExecuteActionFilterAsync>b__0(HttpResponseMessage response)\r\n at System.Threading.Tasks.TaskHelpersExtensions.<>c__DisplayClass41`2.<Then>b__40(Task`1 t)\r\n at System.Threading.Tasks.TaskHelpersExtensions.ThenImpl[TTask,TOuterResult](TTask task, Func`2 continuation, CancellationToken cancellationToken, Boolean runSynchronously)"}
WorkOrders is Dbset on context:
public DbSet<WorkOrder> WorkOrders { get; set; }
I have also tried explicitly casting it to IQueryable, with no change:
[HttpGet]
public IQueryable<WorkOrder> WorkOrders()
{
return (IQueryable<WorkOrder>)_contextProvider.Context.WorkOrders;
}
The only thing that works for me is:
[HttpGet]
public IEnumerable WorkOrders()
{
return _contextProvider.Context.WorkOrders.AsEnumerable();
}
This, however causes another problem for me on the client side, described in this question.
Just a guess here, but can you try using the latest breeze (v 0.82.1) with the following attribute.
[BreezeController]
instead of these
[JsonFormatter, ODataActionFilter]
The new [BreezeController] attribute is a complete replacement for the other two and avoids some other issues.
I have the following action in my Web api controller:
// POST api/<controller>
[AllowAnonymous]
[HttpPost]
public bool Post(string user, string password)
{
return true;
}
I am getting the following error with a 404 status when hitting it with either fiddler or a test jQuery script:
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost/amsi-v8.0.0/api/account'.","MessageDetail":"No action was found on the controller 'Account' that matches the request."}
My http route is as follows:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Gets work fine. I found another question here which talks about removing WebDAV from IIS. I tried that, still same issue.
Why do I get a 404?
The default action selection behavior in ASP.NET Web API cares about your action method parameters as well. If they are simple type objects and they are not optional, you will need to supply them in order to invoke that particular action method. In your case, you should send a request against a URI as below:
/api/account?user=Foo&password=bar
If you wanna get these values inside the request body rather than the query string (which is a better idea), just create a User object and send the request accordingly:
public class User {
public string Name {get;set;}
public string Password {get;set;}
}
Request:
POST http://localhost:8181/api/account HTTP/1.1
Content-Type: application/json
Host: localhost:8181
Content-Length: 33
{"Name": "foo", "Password":"bar"}
And your action method should look like something below:
public HttpResponseMessage Post(User user) {
//do what u need to do here
//return back the proper response.
//e.g: If you have created something, return back 201
return new HttpResponseMessage(HttpStatusCode.Created);
}
When we are posting a json it expect a class so create class in model folder like this
public class Credential
{
public string username { get; set; }
public string password { get;set; }
}
and now change the parameter
[HttpPost]
public bool Post(Credential credential)
{
return true;
}
Try now everything will work smooth