Request.IsAjaxRequest() alternative in MVC6 - asp.net-core

I am trying to run this example Rendering Partial Views using ajax, but i got the following compilation error:
'HttpRequest' does not contain a definition for 'IsAjaxRequest' and no extension method 'IsAjaxRequest' accepting a first argument of type 'HttpRequest' could be found.
public ActionResult ItemsList(string ID)
{
Item item = Service.GetItemById(ID);
if (Request.IsAjaxRequest())
{
return PartialView("viewPath", item);
}
else
{
return View("viewPath", item);
}
}

Check the user agent, as this:
var isAjax = Request.Headers["X-Requested-With"] == "XMLHttpRequest";

Ricardo Peres's answer works for ajax requests but misses the new Fetch types. This works for me:
internal static class RequestHelpers
{
internal static bool IsAjaxRequest(this HttpRequest request)
{
return string.Equals(request.Query["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal) ||
string.Equals(request.Headers["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal) ||
string.Equals(request.Headers["X-Requested-With"], "Fetch", StringComparison.Ordinal);
}
}

Related

How to pass Location header to response with command(API) and query(odata) controllers

Scenario
Hi I have command API controller written in ASP.Net core 2.2. Controller inherited from ControllerBase and has attribute ApiController. I would like to add Location header. I have also query odata controller. Odata version: 7.2.2.
Odata codes:
My Odata controller:
[ODataRoutePrefix("categories")]
public class ODataCategoriesController : ODataController
Odata Get action:
[EnableQuery]
[ODataRoute("{id}")]
public async Task<ActionResult<Category>> GetAsync(Guid id)
Startup
opt.EnableEndpointRouting = false;
...
app.UseHttpsRedirection();
app.UseMvc(options =>
{
options.EnableDependencyInjection();
options.Select().Filter().OrderBy().Count().Expand().MaxTop(100).SkipToken();
options.MapODataServiceRoute("odata", "api/odata", GetExplicitEdmModel());
});
Tried
I've tried using CreatedAtAction but I received: InvalidOperationException: No route matches the supplied values.
In my POST controller:
return CreatedAtAction("Get", "ODataCategories", new { id= categoryResponse.Id }, categoryResponse);
Tried 2
I have also tried with return Location header manually. But I recieved:
Header is not present in response.
Code
[HttpPost]
[ProducesResponseType((int)HttpStatusCode.Created)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<ActionResult<CreateCategoryResponse>> PostCategory(
[FromBody]CreateCategoryCommand createCategoryCommand)
{
CreateCategoryResponse categoryResponse =
await _mediator.Send(createCategoryCommand);
if (categoryResponse == null)
{
return BadRequest();
}
HttpContext.Response.Headers["Location"] =
$"SomeBuiltLocation";
return Created("", categoryResponse);
}
Summary
I am looking for solution which enable me to include Location header. It does not matter if it be with CreatedAt or by hand.
Should be able to create it by hand as well.
[HttpPost]
[ProducesResponseType((int)HttpStatusCode.Created)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<ActionResult<CreateCategoryResponse>> PostCategory(
[FromBody]CreateCategoryCommand createCategoryCommand) {
CreateCategoryResponse categoryResponse =
await _mediator.Send(createCategoryCommand);
if (categoryResponse == null) {
return BadRequest();
}
var result = new CreatedResult("SomeBuiltLocation", categoryResponse);
return result;
}

What is the best possible way to send custom error responses in .net core web api

I'm making a .net Core WebApi using .Net Core 2.2. The API is ready but the failure message and response is where I'm stuck at.
Right now, I'm getting respose like below
json
{
"empId":1999,
"empName":"Conroy, Deborah",
"enrollmentStatus":true,
"primaryFingerprintScore":65,
"secondaryFingerprintScore":60,
"primaryFingerprint":null,
"secondaryFingerprint":null,
"primaryFingerprintType":null,
"secondaryFingerprintType":null}
}
I created a json formatter class and wrote the below code
public class SuperJsonOutputFormatter : JsonOutputFormatter
{
public SuperJsonOutputFormatter(
JsonSerializerSettings serializerSettings,
ArrayPool<char> charPool) : base(serializerSettings, charPool)
{
}
public override async Task WriteResponseBodyAsync(
OutputFormatterWriteContext context,
Encoding selectedEncoding)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
if (selectedEncoding == null)
throw new ArgumentNullException(nameof(selectedEncoding));
using (TextWriter writer =
context.WriterFactory(
context.HttpContext.Response.Body,
selectedEncoding))
{
var rewrittenValue = new
{
resultCode = context.HttpContext.Response.StatusCode,
resultMessage =
((HttpStatusCode)context.HttpContext.Response.StatusCode)
.ToString(),
result = context.Object
};
this.WriteObject(writer, rewrittenValue);
await writer.FlushAsync();
}
}
I expect all the error codes to be sent as generic error messages like the JSON below.
FOR STATUS OKAY:
{
"status" : True,
"error" : null,
"data" : {
{
"empId":1999,
"empName":"Conroy, Deborah",
"enrollmentStatus":true,
"primaryFingerprintScore":65,
"secondaryFingerprintScore":60,
"primaryFingerprint":null,
"secondaryFingerprint":null,
"primaryFingerprintType":null,
"secondaryFingerprintType":null}
}
}
}
FOR OTHER STATUS LIKE 404, 500, 400, 204
{
"status" : False,
"error" : {
"error code" : 404,
"error description" : Not Found
},
"data" : null
}
I expect all the error codes to be sent as generic error messages like the JSON below
You're almost there. What you need to do is enabling your SuperJsonOutputFormatter.
A Little Change to Your Formatter
Firstly, your formatter didn't return a json with the same schema as you want. So I create a dummy class to hold the information for error code and error description:
public class ErrorDescription{
public ErrorDescription(HttpStatusCode statusCode)
{
this.Code = (int)statusCode;
this.Description = statusCode.ToString();
}
[JsonProperty("error code")]
public int Code {get;set;}
[JsonProperty("error description")]
public string Description {get;set;}
}
And change your WriteResponseBodyAsync() method as below:
...
using (TextWriter writer = context.WriterFactory(context.HttpContext.Response.Body, selectedEncoding)) {
var statusCode = context.HttpContext.Response.StatusCode;
var rewrittenValue = new {
status = IsSucceeded(statusCode),
error = IsSucceeded(statusCode) ? null : new ErrorDescription((HttpStatusCode)statusCode),
data = context.Object,
};
this.WriteObject(writer, rewrittenValue);
await writer.FlushAsync();
}
Here the IsSucceeded(statusCode) is a simple helper method that you can custom as you need:
private bool IsSucceeded(int statusCode){
// I don't think 204 indicates that's an error.
// However, you could comment out it if you like
if(statusCode >= 400 /* || statusCode==204 */ ) { return false; }
return true;
}
Enable your Formatter
Secondly, to enable your custom Formatter, you have two approaches: One way is to register it as an global Formatter, the other way is to enable it for particular Controller or Action. Personally, I believe the 2nd way is better. So I create a Action Filter to enable your formatter.
Here's an implementation of the Filter that enables your custom formatter dynamically:
public class SuperJsonOutputFormatterFilter : IAsyncActionFilter{
private readonly SuperJsonOutputFormatter _formatter;
// inject your SuperJsonOutputFormatter service
public SuperJsonOutputFormatterFilter(SuperJsonOutputFormatter formatter){
this._formatter = formatter;
}
// a helper method that provides an ObjectResult wrapper over the raw object
private ObjectResult WrapObjectResult(ActionExecutedContext context, object obj){
var wrapper = new ObjectResult(obj);
wrapper.Formatters.Add(this._formatter);
context.Result= wrapper;
return wrapper;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
ActionExecutedContext resultContext = await next();
// in case we get a 500
if(resultContext.Exception != null && ! resultContext.ExceptionHandled){
var ewrapper = this.WrapObjectResult(resultContext, new {});
ewrapper.StatusCode = (int) HttpStatusCode.InternalServerError;
resultContext.ExceptionHandled = true;
return;
}
else {
switch(resultContext.Result){
case BadRequestObjectResult b : // 400 with an object
var bwrapper=this.WrapObjectResult(resultContext,b.Value);
bwrapper.StatusCode = b.StatusCode;
break;
case NotFoundObjectResult n : // 404 with an object
var nwrapper=this.WrapObjectResult(resultContext,n.Value);
nwrapper.StatusCode = n.StatusCode;
break;
case ObjectResult o : // plain object
this.WrapObjectResult(resultContext,o.Value);
break;
case JsonResult j : // plain json
this.WrapObjectResult(resultContext,j.Value);
break;
case StatusCodeResult s: // other statusCodeResult(including NotFound,NoContent,...), you might want to custom this case
var swrapper = this.WrapObjectResult(resultContext, new {});
swrapper.StatusCode = s.StatusCode;
break;
}
}
}
}
And don't forget to register your formatter as a service :
services.AddScoped<SuperJsonOutputFormatter>();
Finally, when you want to enable your formatter, just add a [TypeFilter(typeof(SuperJsonOutputFormatterFilter))] annotation for the controller or action.
Demo
Let's create an action method for Test:
[TypeFilter(typeof(SuperJsonOutputFormatterFilter))]
public IActionResult Test(int status)
{
// test json result(200)
if(status == 200){ return Json(new { Id = 1, }); }
// test 400 object result
else if(status == 400){ return BadRequest( new {}); }
// test 404 object result
else if(status == 404){ return NotFound(new { Id = 1, }); }
// test exception
else if(status == 500){ throw new Exception("unexpected exception"); }
// test status code result
else if(status == 204){ return new StatusCodeResult(204); }
// test normal object result(200)
var raw = new ObjectResult(new XModel{
empId=1999,
empName = "Conroy, Deborah",
enrollmentStatus=true,
primaryFingerprintScore=65,
secondaryFingerprintScore=60,
primaryFingerprint = null,
secondaryFingerprint= null,
primaryFingerprintType=null,
secondaryFingerprintType=null
});
return raw;
}
Screenshot:

Advantage of using IActionResult as result type in Actions

What's the advantage or recommendation on using IActionResult as the return type of a WebApi controller instead of the actual type you want to return?
Most of the examples I've seen return IActionResult, but when I build my first site I exclusively use View Model classes as my return types.... now I feel like I did it all wrong!
The main advantage is that you can return error/status codes or redirects/resource urls.
For example:
public IActionResult Get(integer id)
{
var user = db.Users.Where(u => u.UserId = id).FirstOrDefault();
if(user == null)
{
// Returns HttpCode 404
return NotFound();
}
// returns HttpCode 200
return ObjectOk(user);
}
or
public IActionResult Create(User user)
{
if(!ModelState.IsValid)
{
// returns HttpCode 400
return BadRequest(ModelState);
}
db.Users.Add(user);
db.SaveChanges();
// returns HttpCode 201
return CreatedAtActionResult("User", "Get", new { id = user.Id} );
}
The main advantage is that you can easily test your code using a mocking framework.
And as you build your controllers, you can easily change your return object as well. IActionResult is a interface and has many implementations like JsonResult, ViewResult, FileResult and so on.

MVC4 add overload to a method

As many of you know MVC4 has some great new features, I am struggling with the ContextDependentView trying to add an overload to it. I get an error saying no overload method for ContextDependentView takes 1 argument . My original code that was working was this
// This worked fine
return View(new ModelSample { getInfo= info, Retrieving= Retrieve })
// This is now what I have tried to do that doesn't work
return ContextDependentView(new ModelSample { getInfo= info, Retrieving= Retrieve })
//This is the method for ContextDependentView()
private ActionResult ContextDependentView()
{
string actionName = ControllerContext.RouteData.GetRequiredString("action");
if (Request.QueryString["content"] != null)
{
ViewBag.FormAction = "Json" + actionName;
return PartialView();
}
else
{
ViewBag.FormAction = actionName;
return View();
}
}
I obviously see that there are no overloads but how can I add an overload to the ContextDependentView method to accept my model like return View()..thanks
Add this overload to your controller:
private ActionResult ContextDependentView(SampleModel model)
{
string actionName = ControllerContext.RouteData.GetRequiredString("action");
if (Request.QueryString["content"] != null)
{
ViewBag.FormAction = "Json" + actionName;
return PartialView();
}
else
{
ViewBag.FormAction = actionName;
return View();
}
}
That should work...

Struts2 more than one action in one class

I'm using Struts2. I have two web forms that have the same code. I would like to eliminate one form. Here is the structure of my Struts project.
\Web Pages
form.jsp
\WEB-INF
\Content
error.jsp
form.jsp
success.jsp
\Source Packages
\action
MyAction.java
MyAction.java
package action;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.*;
public class MyAction extends ActionSupport {
#Action(value = "foo", results = {
#Result(name = "input", location = "form.jsp"),
#Result(name = "success", location = "success.jsp"),
#Result(name = "error", location = "error.jsp")
})
public String execute() throws Exception {
if (user.length() == 1) {
return "success";
} else {
return "error";
}
}
private String user = "";
public void validate() {
if (user.length() == 0) {
addFieldError("user", getText("user required"));
}
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}
I tried to eliminate form.jsp under \Web Pages by adding a new action method to MyAction.java.
#Action(value="bar", results = {
#Result(name = "success", location = "form.jsp"),
})
public String another() {
return "success";
}
But I got the following error when I go to http : //localhost .../bar.action
HTTP Status 404 - No result defined for action action.MyAction and result input
Your MyAction has an implementation of validate(), which means it is validation aware.
What's happening is that you're calling another, but validate() is kicking in (as it's in the interceptor stack). Validation is failing, and therefore sending to INPUT result, which is not defined in another.
You should
Add #SkipValidation to the another method if you don't want validation there
Add the INPUT result to another() if you want a default input result
On a more general note, when you get that kind of error (No result defined for action X and result input) it usually means you're either having validation errors, parameter population errors (eg: an exception in preparable).