Pass request context during RedirectToAction c# - c#

I am using RedirectToAction method of the base API controller. The first controller needs to modify the request headers (which I seem to be able to do) but the change is not retained.
This is a simplified implementation of what I am trying to do.
[HttpGet]
public IActionResult Get(string str)
{
// The request comes with a request header with key "Authorization" and value "ABC"
HttpContext.Request.Headers.Remove("Authorization");
HttpContext.Request.Headers.Add("Authorization", "XYZ");
return RedirectToAction("B");
}
[HttpGet]
public IActionResult B()
{
var value = HttpContext.Request.Headers.First(x => x.Key == "Authorization"); // I want this to be ""XYZ" , but it remains "ABC"
return Ok();
}
Any ideas on how I can get the second Action to use the Request header I updated in the first Action.
Edit:
All our Controllers / Actions are Authenticated using Core middleware JWT Auth Policy
Only Action one allows Anonymous access.
Action one is called from an internal related solution with a "Code" (Which is used to create a JWT token) .
All other Actions require the JWT for Authentication.
The "Code" and JWT Token have independent expires and also hold some data.
The info in the "Code" is deemed more up to date. Action one can be called with both a "Code" and a JWT token.
The redirect was my way of flushing out old JWT token.
When action one is called with a valid "Code" a new JWT is created. I then want to redirect to a controller that will validate the JWT token (using middleware).
I know I can do this manually, but trying to trigger core middleware.

RedirectToAction returns a 302 response to the browser, which tells the browser to start a new request to the new URL. So your code in B() is hit after the browser initiated a whole new request. So the Request object you're looking at in B() is completely different than the one you modified in Get().
That's clearly not what you want to do. Instead of redirecting, just return B():
[HttpGet]
public IActionResult Get(string str)
{
// The request comes with a request header with key "Authorization" and value "ABC"
HttpContext.Request.Headers.Remove("Authorization");
HttpContext.Request.Headers.Add("Authorization", "XYZ");
return B();
}
But something does feel wrong about rewriting the request headers. It's kind of like rewriting history. Another way is to use HttpContext.Items to store a value:
[HttpGet]
public IActionResult Get(string str)
{
HttpContext.Items["Authorization"] = "XYZ";
return B();
}
[HttpGet]
public IActionResult B()
{
var value = HttpContext.Items["Authorization"] as string ?? HttpContext.Request.Headers.First(x => x.Key == "Authorization");
return Ok();
}
The values in HttpContext.Items exist for the life of a single request.
If you must redirect, then you can use TempData to hold data until it's read in the next request:
[HttpGet]
public IActionResult Get(string str)
{
TempData["Authorization"] = "XYZ";
return RedirectToAction("B");
}
[HttpGet]
public IActionResult B()
{
if (TempData.Contains("Authorization")) {
HttpContext.Request.Headers.Remove("Authorization");
HttpContext.Request.Headers.Add("Authorization", TempData["Authorization"]);
}
var value = HttpContext.Request.Headers.First(x => x.Key == "Authorization");
return Ok();
}

Related

How to make a PATCH request to am API with ASP.NET Core 2.2?

I have an application that is written using C# on the top of ASP.NET Core 2.2. I created a controller that responds to a PATCH request called Update. Here is my controller
[Route("api/[controller]"), ApiController, Produces("application/json")]
public class CategoriesController : ControllerBase
{
[HttpPatch("{propertyId}/{listId}/{isOn}"), Authorize]
public ActionResult<bool> Update(int propertyId, int listId, bool isOn)
{
// Do something
return true;
}
}
also, to return a 401 error when the user isn't authorized instead of a redirect, I added the following code to my Startup class
services.ConfigureApplicationCookie(config =>
{
config.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = ctx =>
{
if (ctx.Request.Path.StartsWithSegments("/api", StringComparison.CurrentCultureIgnoreCase))
{
ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
else
{
ctx.Response.Redirect(ctx.RedirectUri);
}
return Task.FromResult(0);
}
};
});
Now to call this API using jQuery I did the following
$('.update-property').click(function (e) {
e.preventDefault();
var obj = $(this);
$.ajax({
url: '/api/Categories/Update',
type: 'PATCH',
data: {
'propertyId': obj.data('property-id'),
'listId': obj.data('list-id'),
'isOn': obj.data('is-on') === 'True' ? 'false' : 'true'
},
success: function (response) {
console.log(response);
// if response unauthorized, redirect to the login page with the ReturnUrl
// else if response.data is true then change the icon
}
});
});
But this request keeps returning a 404 http error code. I inspected this question in the developer tools and I see that the parameter are being set correctly and the URL is valid.
How can I correctly handle this PATCH request?
[Route("api/[controller]"), ApiController, Produces("application/json")]
public class CategoriesController : ControllerBase
{
[HttpPatch("{propertyId}/{listId}/{isOn}"), Authorize]
public ActionResult<bool> Update(int propertyId, int listId, bool isOn)
The route templates here determine the URL for your Update endpoint. In this case, the resulting URL template would be this:
api/Categories/{propertyId}/{listId}/{isOn}
So for example, a valid URL for this endpoint would be /api/Categories/12/34/true.
If you don’t want to pass the values as parameters (since you already pass them in the body), you have to change the route template. For example, you could just remove the route template on the action method:
[HttpPatch, Authorize]
public ActionResult<bool> Update(int propertyId, int listId, bool isOn)
// …
Then, the URL would be just api/Categories.
Of course, you could also make api/Categories/Update the URL for the endpoint, but with REST, it’s usually not recommended to have method names in the URL. A PATCH request usually means “update this resource” and then you would be pointing to the URL of the resource.
you need to send request with localhost:44313/api/Categories url. Don't put update prefix. You just need to send Patch request to your localhost:44313/api/Categories endpoint.
with Parameters
localhost:44313/api/Categories/{propertyId}/{listId}/{isOn}

How to use a parameter in Web API v2?

I have no idea where to start with this. I asked a question previously, and someone suggested I look at attribute routing. I read up on it, and while it helped me to create the below code, I'm still not sure how to limit it like I want to.
public class ReviewController : ApiController
{
private Review db = new Review();
////This GET works. It was auto-generated by Visual Studio.
// GET: api/Review
public IQueryable<Review> GetReview()
{
return db.Review;
}
////This is the GET that I'm trying to write, but don't know what to do
// GET: api
[Route("api/review/site")]
[HttpGet]
public IEnumerable<Review> FindStoreBySite(int SiteID)
{
return db.Review
}
////This GET also works and was generated by VS.
// GET: api/Review/5
[ResponseType(typeof(Review))]
public IHttpActionResult GetReview(int id)
{
Review review = db.Review.Find(id);
if (review == null)
{
return NotFound();
}
return Ok(review);
}
Essentially what I'm aiming to do is to limit what's returned by the API to only the results where the SiteID is equal to whatever value is passed into the URL. I'm not even sure where to get started with this, and googling/searching stack overflow for "what to put in web api return" has been fruitless.
How do I tell the API what I want to have returned based off a parameter besides ReviewID?
Edit: I've updated the code per the suggestions in the answer below, but now I'm getting a new error.
Here's the current code:
private ReviewAPIModel db = new ReviewAPIModel();
// GET: api/Review
[Route("api/Review")]
[HttpGet]
public IQueryable<Review> GetReview()
{
return db.Review;
}
// GET: api
[Route("api/Review/site/{siteid}")]
[HttpGet]
public IEnumerable<Review> FindStoreBySite(int siteid)
{
return db.Review.Where(Review => Review.SiteID == siteid);
}
// GET: api/Review/5
[ResponseType(typeof(Review))]
public IHttpActionResult GetReview(int id)
{
Review review = db.Review.Find(id);
if (review == null)
{
return NotFound();
}
return Ok(review);
}
}
Here's the error that I get:
Multiple actions were found that match the request
When I google it, it takes me to this question: Multiple actions were found that match the request in Web Api
However, I've tried the answers there (I've confirmed that I'm using Web API V2, and my webapiconfig.cs file includes the config.MapHttpAttributeRoutes(); line.
In addition, as you can see in my code above, I've included the appropriate routing. However, I'm still getting an error telling me that it's returning two conflicting API calls.
To pass parameters to a WebApi controller you need to add a [Route()] attribute to that controller and mark the part of the link that's used as the attribute with this {}.
To return reviews that only match the passed in parameter you need to use LINQ to filter the data.
Here is an example:
[Route("api/getFoo/{id}")]
public IHttpActionResult GetFoo(int id)
{
return db.Foo.Where(x => x.Id == id);
}
The {id} part of the string represents the id that will be in the url in your browser: http://localhost:51361/api/getFoo/2. The "2" in the url IS the {id} property that you marked in your [Route("api/getFoo/{id}")] attribute.
I also modified your code:
public class ReviewController : ApiController
{
...
[Route("api/review/site/{siteId}")]
[HttpGet]
public IEnumerable<Review> FindStoreBySite(int SiteID)
{
return db.Review.Where(review => review.Id == SiteID);
}
...
Your request url should look somewhat like this: http://localhost:51361/api/review/site?SiteID=2
This can be difficult to wrap your head around at first but you'll get used to it eventually. It's how arguments are passed to Controller Action parameters.
if you want to get parameters for GET, it's like a simple overload, but if it's done, POST is with [fromBody], because the URL is in the tag [Route ("/abc/123/{id}")]
example
code
[Route ("/abc/123/{idSite}")]
[HttpGet]
public HttpResponseMessage ControllerIdSite(int IdSite){
//CODE . . .
return Request.CreateResponse<int>(HttpStatusCode.OK, IdSite);
}
call
/abc/123/17
return
17
OR
[Route ("/abc/123")]
[HttpGet]
public HttpResponseMessage ControllerIdSite(int IdSite){
//CODE . . .
return Request.CreateResponse<int>(HttpStatusCode.OK, IdSite);
}
call
/abc/123?IdSite=17
return
17

ASP.NET Core return JSON with status code

I'm looking for the correct way to return JSON with a HTTP status code in my .NET Core Web API controller. I use to use it like this:
public IHttpActionResult GetResourceData()
{
return this.Content(HttpStatusCode.OK, new { response = "Hello"});
}
This was in a 4.6 MVC application but now with .NET Core I don't seem to have this IHttpActionResult I have ActionResult and using like this:
public ActionResult IsAuthenticated()
{
return Ok(Json("123"));
}
But the response from the server is weird, as in the image below:
I just want the Web API controller to return JSON with a HTTP status code like I did in Web API 2.
The most basic version responding with a JsonResult is:
// GET: api/authors
[HttpGet]
public JsonResult Get()
{
return Json(_authorRepository.List());
}
However, this isn't going to help with your issue because you can't explicitly deal with your own response code.
The way to get control over the status results, is you need to return a ActionResult which is where you can then take advantage of the StatusCodeResult type.
for example:
// GET: api/authors/search?namelike=foo
[HttpGet("Search")]
public IActionResult Search(string namelike)
{
var result = _authorRepository.GetByNameSubstring(namelike);
if (!result.Any())
{
return NotFound(namelike);
}
return Ok(result);
}
Note both of these above examples came from a great guide available from Microsoft Documentation: Formatting Response Data
Extra Stuff
The issue I come across quite often is that I wanted more granular control over my WebAPI rather than just go with the defaults configuration from the "New Project" template in VS.
Let's make sure you have some of the basics down...
Step 1: Configure your Service
In order to get your ASP.NET Core WebAPI to respond with a JSON Serialized Object along full control of the status code, you should start off by making sure that you have included the AddMvc() service in your ConfigureServices method usually found in Startup.cs.
It's important to note thatAddMvc() will automatically include the Input/Output Formatter for JSON along with responding to other request types.
If your project requires full control and you want to strictly define your services, such as how your WebAPI will behave to various request types including application/json and not respond to other request types (such as a standard browser request), you can define it manually with the following code:
public void ConfigureServices(IServiceCollection services)
{
// Build a customized MVC implementation, without using the default AddMvc(), instead use AddMvcCore().
// https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc/MvcServiceCollectionExtensions.cs
services
.AddMvcCore(options =>
{
options.RequireHttpsPermanent = true; // does not affect api requests
options.RespectBrowserAcceptHeader = true; // false by default
//options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
//remove these two below, but added so you know where to place them...
options.OutputFormatters.Add(new YourCustomOutputFormatter());
options.InputFormatters.Add(new YourCustomInputFormatter());
})
//.AddApiExplorer()
//.AddAuthorization()
.AddFormatterMappings()
//.AddCacheTagHelper()
//.AddDataAnnotations()
//.AddCors()
.AddJsonFormatters(); // JSON, or you can build your own custom one (above)
}
You will notice that I have also included a way for you to add your own custom Input/Output formatters, in the event you may want to respond to another serialization format (protobuf, thrift, etc).
The chunk of code above is mostly a duplicate of the AddMvc() method. However, we are implementing each "default" service on our own by defining each and every service instead of going with the pre-shipped one with the template. I have added the repository link in the code block, or you can check out AddMvc() from the GitHub repository..
Note that there are some guides that will try to solve this by "undoing" the defaults, rather than just not implementing it in the first place... If you factor in that we're now working with Open Source, this is redundant work, bad code and frankly an old habit that will disappear soon.
Step 2: Create a Controller
I'm going to show you a really straight-forward one just to get your question sorted.
public class FooController
{
[HttpPost]
public async Task<IActionResult> Create([FromBody] Object item)
{
if (item == null) return BadRequest();
var newItem = new Object(); // create the object to return
if (newItem != null) return Ok(newItem);
else return NotFound();
}
}
Step 3: Check your Content-Type and Accept
You need to make sure that your Content-Type and Accept headers in your request are set properly. In your case (JSON), you will want to set it up to be application/json.
If you want your WebAPI to respond as JSON as default, regardless of what the request header is specifying you can do that in a couple ways.
Way 1
As shown in the article I recommended earlier (Formatting Response Data) you could force a particular format at the Controller/Action level. I personally don't like this approach... but here it is for completeness:
Forcing a Particular Format If you would like to restrict the response formats for a specific action you can, you can apply the
[Produces] filter. The [Produces] filter specifies the response
formats for a specific action (or controller). Like most Filters, this
can be applied at the action, controller, or global scope.
[Produces("application/json")]
public class AuthorsController
The [Produces] filter will force all actions within the
AuthorsController to return JSON-formatted responses, even if other
formatters were configured for the application and the client provided
an Accept header requesting a different, available format.
Way 2
My preferred method is for the WebAPI to respond to all requests with the format requested. However, in the event that it doesn't accept the requested format, then fall-back to a default (ie. JSON)
First, you'll need to register that in your options (we need to rework the default behavior, as noted earlier)
options.RespectBrowserAcceptHeader = true; // false by default
Finally, by simply re-ordering the list of the formatters that were defined in the services builder, the web host will default to the formatter you position at the top of the list (ie position 0).
More information can be found in this .NET Web Development and Tools Blog entry
You have predefined methods for most common status codes.
Ok(result) returns 200 with response
CreatedAtRoute returns 201 + new resource URL
NotFound returns 404
BadRequest returns 400 etc.
See BaseController.cs and Controller.cs for a list of all methods.
But if you really insist you can use StatusCode to set a custom code, but you really shouldn't as it makes code less readable and you'll have to repeat code to set headers (like for CreatedAtRoute).
public ActionResult IsAuthenticated()
{
return StatusCode(200, "123");
}
With ASP.NET Core 2.0, the ideal way to return object from Web API (which is unified with MVC and uses same base class Controller) is
public IActionResult Get()
{
return new OkObjectResult(new Item { Id = 123, Name = "Hero" });
}
Notice that
It returns with 200 OK status code (it's an Ok type of ObjectResult)
It does content negotiation, i.e. it'll return based on Accept header in request. If Accept: application/xml is sent in request, it'll return as XML. If nothing is sent, JSON is default.
If it needs to send with specific status code, use ObjectResult or StatusCode instead. Both does the same thing, and supports content negotiation.
return new ObjectResult(new Item { Id = 123, Name = "Hero" }) { StatusCode = 200 };
return StatusCode( 200, new Item { Id = 123, Name = "Hero" });
or even more fine grained with ObjectResult:
Microsoft.AspNetCore.Mvc.Formatters.MediaTypeCollection myContentTypes = new Microsoft.AspNetCore.Mvc.Formatters.MediaTypeCollection { System.Net.Mime.MediaTypeNames.Application.Json };
String hardCodedJson = "{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";
return new ObjectResult(hardCodedJson) { StatusCode = 200, ContentTypes = myContentTypes };
If you specifically want to return as JSON, there are couple of ways
//GET http://example.com/api/test/asjson
[HttpGet("AsJson")]
public JsonResult GetAsJson()
{
return Json(new Item { Id = 123, Name = "Hero" });
}
//GET http://example.com/api/test/withproduces
[HttpGet("WithProduces")]
[Produces("application/json")]
public Item GetWithProduces()
{
return new Item { Id = 123, Name = "Hero" };
}
Notice that
Both enforces JSON in two different ways.
Both ignores content negotiation.
First method enforces JSON with specific serializer Json(object).
Second method does the same by using Produces() attribute (which is a ResultFilter) with contentType = application/json
Read more about them in the official docs. Learn about filters here.
The simple model class that is used in the samples
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
The easiest way I came up with is :
var result = new Item { Id = 123, Name = "Hero" };
return new JsonResult(result)
{
StatusCode = StatusCodes.Status201Created // Status code here
};
This is my easiest solution:
public IActionResult InfoTag()
{
return Ok(new {name = "Fabio", age = 42, gender = "M"});
}
or
public IActionResult InfoTag()
{
return Json(new {name = "Fabio", age = 42, gender = "M"});
}
Awesome answers I found here and I also tried this return statement see StatusCode(whatever code you wish) and it worked!!!
return Ok(new {
Token = new JwtSecurityTokenHandler().WriteToken(token),
Expiration = token.ValidTo,
username = user.FullName,
StatusCode = StatusCode(200)
});
Instead of using 404/201 status codes using enum
public async Task<IActionResult> Login(string email, string password)
{
if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password))
{
return StatusCode((int)HttpStatusCode.BadRequest, Json("email or password is null"));
}
var user = await _userManager.FindByEmailAsync(email);
if (user == null)
{
return StatusCode((int)HttpStatusCode.BadRequest, Json("Invalid Login and/or password"));
}
var passwordSignInResult = await _signInManager.PasswordSignInAsync(user, password, isPersistent: true, lockoutOnFailure: false);
if (!passwordSignInResult.Succeeded)
{
return StatusCode((int)HttpStatusCode.BadRequest, Json("Invalid Login and/or password"));
}
return StatusCode((int)HttpStatusCode.OK, Json("Sucess !!!"));
}
Controller action return types in ASP.NET Core web API
02/03/2020
6 minutes to read
+2
By Scott Addie Link
Synchronous action
[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<Product> GetById(int id)
{
if (!_repository.TryGetProduct(id, out var product))
{
return NotFound();
}
return product;
}
Asynchronous action
[HttpPost]
[Consumes(MediaTypeNames.Application.Json)]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<Product>> CreateAsync(Product product)
{
if (product.Description.Contains("XYZ Widget"))
{
return BadRequest();
}
await _repository.AddProductAsync(product);
return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
}
Please refer below code, You can manage multiple status code with different type JSON
public async Task<HttpResponseMessage> GetAsync()
{
try
{
using (var entities = new DbEntities())
{
var resourceModelList = entities.Resources.Select(r=> new ResourceModel{Build Your Resource Model}).ToList();
if (resourceModelList.Count == 0)
{
return this.Request.CreateResponse<string>(HttpStatusCode.NotFound, "No resources found.");
}
return this.Request.CreateResponse<List<ResourceModel>>(HttpStatusCode.OK, resourceModelList, "application/json");
}
}
catch (Exception ex)
{
return this.Request.CreateResponse<string>(HttpStatusCode.InternalServerError, "Something went wrong.");
}
}
What I do in my Asp Net Core Api applications it is to create a class that extends from ObjectResult and provide many constructors to customize the content and the status code.
Then all my Controller actions use one of the costructors as appropiate.
You can take a look at my implementation at:
https://github.com/melardev/AspNetCoreApiPaginatedCrud
and
https://github.com/melardev/ApiAspCoreEcommerce
here is how the class looks like(go to my repo for full code):
public class StatusCodeAndDtoWrapper : ObjectResult
{
public StatusCodeAndDtoWrapper(AppResponse dto, int statusCode = 200) : base(dto)
{
StatusCode = statusCode;
}
private StatusCodeAndDtoWrapper(AppResponse dto, int statusCode, string message) : base(dto)
{
StatusCode = statusCode;
if (dto.FullMessages == null)
dto.FullMessages = new List<string>(1);
dto.FullMessages.Add(message);
}
private StatusCodeAndDtoWrapper(AppResponse dto, int statusCode, ICollection<string> messages) : base(dto)
{
StatusCode = statusCode;
dto.FullMessages = messages;
}
}
Notice the base(dto) you replace dto by your object and you should be good to go.
I got this to work. My big issue was my json was a string (in my database...and not a specific/known Type).
Ok, I finally got this to work.
////[Route("api/[controller]")]
////[ApiController]
////public class MyController: Microsoft.AspNetCore.Mvc.ControllerBase
////{
//// public IActionResult MyMethod(string myParam) {
string hardCodedJson = "{}";
int hardCodedStatusCode = 200;
Newtonsoft.Json.Linq.JObject job = Newtonsoft.Json.Linq.JObject.Parse(hardCodedJson);
/* "this" comes from your class being a subclass of Microsoft.AspNetCore.Mvc.ControllerBase */
Microsoft.AspNetCore.Mvc.ContentResult contRes = this.Content(job.ToString());
contRes.StatusCode = hardCodedStatusCode;
return contRes;
//// } ////end MyMethod
//// } ////end class
I happen to be on asp.net core 3.1
#region Assembly Microsoft.AspNetCore.Mvc.Core, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
//C:\Program Files\dotnet\packs\Microsoft.AspNetCore.App.Ref\3.1.0\ref\netcoreapp3.1\Microsoft.AspNetCore.Mvc.Core.dll
I got the hint from here :: https://www.jianshu.com/p/7b3e92c42b61
The cleanest solution I have found is to set the following in my ConfigureServices method in Startup.cs (In my case I want the TZ info stripped. I always want to see the date time as the user saw it).
services.AddControllers()
.AddNewtonsoftJson(o =>
{
o.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Unspecified;
});
The DateTimeZoneHandling options are Utc, Unspecified, Local or RoundtripKind
I would still like to find a way to be able to request this on a per-call bases.
something like
static readonly JsonMediaTypeFormatter _jsonFormatter = new JsonMediaTypeFormatter();
_jsonFormatter.SerializerSettings = new JsonSerializerSettings()
{DateTimeZoneHandling = DateTimeZoneHandling.Unspecified};
return Ok("Hello World", _jsonFormatter );
I am converting from ASP.NET and there I used the following helper method
public static ActionResult<T> Ok<T>(T result, HttpContext context)
{
var responseMessage = context.GetHttpRequestMessage().CreateResponse(HttpStatusCode.OK, result, _jsonFormatter);
return new ResponseMessageResult(responseMessage);
}

Unable to fetch returnurl in asp.net mvc Controller

I have two controllers Base and Login.
Base Controller:
public ActionResult start()
{
string action = Request.QueryString[WSFederationConstants.Parameters.Action];
}
Login Controller:
public ActionResult Login(string user,string password,string returnUrl)
{
if (FormsAuthentication.Authenticate(user, password))
{
if (string.IsNullOrEmpty(returnUrl) && Request.UrlReferrer != null)
returnUrl = Server.UrlEncode(Request.UrlReferrer.PathAndQuery);
return RedirectToAction("Start","Base", returnUrl });
}
return View();
}
After authentication is done it gets redirected to Start action in Base Controller as expected.
But the querystring doesnot fetch the value. When hovered over the querystring it shows length value but not the uri.
How to use the url sent from Login controller in Base Controller and fetch parameters from it?
You are actually returning a 302 to the client.
From the docs.
Returns an HTTP 302 response to the browser, which causes the browser
to make a GET request to the specified action.
When doing that the client will make another request with the url that you created. In your case something like youruri.org/Base/Start. Take a look at the network tab in your browser (F12 in Chrome).
What I think you want to do is:
return RedirectToAction
("Start", "Base", new { WSFederationConstants.Parameters.Action = returnUrl });
Assuming that WSFederationConstants.Parameters.Action is a constant. If WSFederationConstants.Parameters.Action returns the string fooUrl your action will return the following to the browser:
Location:/Base/Start?fooUrl=url
Status Code:302 Found
Another option is to actually pass the value to the controller:
public class BaseController: Controller
{
public ActionResult start(string myAction)
{
string localAction = myAction; //myAction is automatically populated.
}
}
And in your redirect:
return RedirectToAction
("Start", "Base", new { myAction = returnUrl });
Then the BaseController will automatically fetch the parameter, and you don't need to fetch it from the querystring.

Web Api 2 bad request

Im a beginner with Web api and Im trying to setup a simple owin selfhosted service that Im trying out.
I've been searching stackoverflow and other places for a while now, but I cant seem to find anything obviously wrong.
The problem I have is that I get a bad request response everytime I try to call my service.
The controller looks like this:
[RoutePrefix("api/ndtdocument")]
public class NDTDocumentsController : ApiController, INDTDocumentsController
{
[HttpGet]
public IHttpActionResult Get()
{
var document = Program.NDTServerSession.GetNextNDTDocument(DateTime.Today);
if (document == null)
return null;
return Ok(document);
}
[Route("")]
public IHttpActionResult Post([FromBody] NDTDocument ndtDocument)
{
try
{
Program.NDTServerSession.AddNDTDocument(ndtDocument);
return Ok();
}
catch(Exception ex)
{
return BadRequest(ex.Message);
}
}
}
And the client looks like this:
static void Main(string[] args)
{
AddNDTDocument(#"C:\Testing.txt");
}
private static void AddNDTDocument(string centralserverPath)
{
var client = GetServerClient();
NDTDocument document = new NDTDocument();
var response = client.PostAsJsonAsync("ndtdocument", document).Result;
}
static HttpClient GetServerClient()
{
var client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:9000/api/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
I can see when I debug it that the request uri is infact http://localhost:9000/api/ndtdocument
But the response is allways bad request and I have a breakpoint in the controller and it is never invoked.
Everytime I try to do something with web apis I Always run into some weird (but simple problem).
Any thoughts?
Thanks!
Web API will decide your route based on your method names. Since you have added [RoutePrefix("api/ndtdocument")] on class level this will be the route to your controller. When web api looks for an action it will match on method names, so in your case your actual route would be http://localhost:9000/api/ndtdocument/post.
When trying to decide what http method that a specific action requires web api will check your method names and methods starting with post will be http post, get will be http get etc.
So lets say we would instead call our method PostData, for starters we could remove the [HttpPost] attribute. Our route would now be http://localhost:9000/api/ndtdocument/postdata. Let's now say that we want our path to be just /data. We would then first rename our method to Data, but now web api does not know what http method we want to invoke this method with, thats why we add the [HttpPost] attribute.
Edit after reading your comment
[Route("{id:int}")]
public IHttpActionResult Get(int id)
[Route("")]
public IHttpActionResult Post([FromBody] NDTDocument ndtDocument)
Okey, after nearly going seriously insane. I found the problem.
I forgot to reference webapi.webhost and then system.web.
After this Everything worked like a charm.
You must use route tags and call this way http://localhost:9000/api/get or http://localhost:9000/api/post
[RoutePrefix("api/ndtdocument")]
public class NDTDocumentsController : ApiController, INDTDocumentsController
{
[HttpGet]
[Route("get")]
public IHttpActionResult Get()
{
var document = Program.NDTServerSession.GetNextNDTDocument(DateTime.Today);
if (document == null)
return null;
return Ok(document);
}
[HttpPost]
[Route("post")]
public IHttpActionResult Post([FromBody] NDTDocument ndtDocument)
{
try
{
Program.NDTServerSession.AddNDTDocument(ndtDocument);
return Ok();
}
catch(Exception ex)
{
return BadRequest(ex.Message);
}
}
}
for more infromation pls check this link

Categories