How can I get web service method being called by HttpContext? - c#

I have web service with 40 different web methods.
Can I get in my web service the Method that the request sent from using HttpContext?
I need it because I have abstract general command that all the methods activate and I have access only to HttpContext.
Thanks!

If I understand correct your question you can use PathInfo property of the HttpRequest:
string methodName = HttpContext.Current.Request.PathInfo;
The string methodName will be the method name with the slash prefix (/): "/MyWebMethod".

You probably need:
HttpContext.Current
But be sure you've the ASPX compatibility mode turned on, otherwise you'll not be able to access that property
You can also save the name of the function into the Items array like this:
void myServiceMethod()
{
HttpContext.Current.Items["MethodName"] = "myServiceMethod";
// ...
// here comes your method implementation
}
and then you can anywhere read the HttpContext.Current.Items["MethodName"]
colection HttpContext.Current.Items is valid always only for current request, so you can use it as a storage for any request related information.
When the request is responded, it's garbage.

Related

Is Request.Cookies["value"] in c# controller some static reference

I am having difficulty to understand some code from GitHub (I am learning angular, however this is server side code written in c#)
The code is available on GitHub code).
I can't completely understand the very first line of code var refreshToken = Request.Cookies["refreshToken"]; Where does Request.Cookies come from? It is not a variable and it looks like a static call to some array Cookies. How does the element of that array happen to contain "refresh-token" item?
Could someone please explain this? (this code comes from the class derived from BaseController)
[HttpPost("refresh-token")]
public ActionResult<AuthenticateResponse> RefreshToken()
{
var refreshToken = Request.Cookies["refreshToken"];
var response = _accountService.RefreshToken(refreshToken, ipAddress());
setTokenCookie(response.RefreshToken);
return Ok(response);
}
When you work in an HTTP application, .NET manages some context for you. A bunch of stuff you write, like your POST action, is provided with an HTTP context, which has properties that provide information about the request. This includes headers, cookies, etc.
When you use Request within an MVC controller (or some other HTTP context) you'll get access to the HttpContext and Request that relates to the specific single request. It feels like magic, but it's the framework doing the work for you.
A bit more information on context.
You need to check other serverside codes which set the cookie,Cookie is created in serverside firstly and sent to User Agent,often stored in your browser.next time you send a request,your request may contain the cookie
you could check the codes like:Response.Cookies.Append(....)

Failed to load resource: the server responded with a status of 404 ()

I am writing a REST API in .net core. I am trying to test the API using Postman and I am getting an error saying
Failed to load resource: the server responded with a status of 404 ()
I know this error occurs when the route does not match. Not sure, what am I doing wrong with the route. Below is my code with the Route at the top:
namespace RecLoad.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class RecLoadPrimeController : ControllerBase
{
[Route("RecLoadPrime/insertRecLoadData/{RecStartDate}/{RecEndDate}")]
[HttpPost]
public void insertRecLoadData(string RecStartDate, string RecEndDate)
{
RecLoadDataProvider dataProvider = new RecLoadDataProvider();
dataProvider.InsertCardsData(RecStartDate, RecEndDate);
}
}
}
The URL that I am trying to test in Postman is below:
https://localhost:44360/api/RecLoadPrime/insertRecLoadData/?RecStartDate=01/01/2020&RecEndDate=01/02/2020
I am very new to API, this is the first API that I am writing. Below is the image for application structure. Its extremely simple:
Any help will be greatly appreciated.
A 404 error means not found. This means Postman cant find the end point you are trying to hit.
Your [Route] attribute needs to be updated. The root of this endpoint (controller) it's RecLoadPrime. So get rid of that part. If you are just trying to test, update it to [Route("insert")].
Using ? in your URL means you are passing query parameters. Which are usually used on GET requests not on POST requests.
Web API expects you to use Model Binding for passing in parameters. Meaning map the post parameters to a strongly typed .NET object, not to single parameters. Alternatively, you can also accept a FormDataCollection parameter on your API method to get a name value collection of all POSTed values.
For example: Create a small class called Card, with the properties startDate, and endDate. Make them DateTime. Now use that in the method signature public void insertRecLoadData([FromBody]Card card)
In Postman, you are now going to use the Body option and create a JSON representation of this new class we created.
For example: { "startDate": "2020-03-23", "endDate": "2020-03-27" }
In the route, you are going to use: POST | https://localhost:44360/api/insertRecLoadData/insert
Make sure you set breakpoints in your controller. Not sure how you have setup your project but I'd suggest reading up more on how to setup a Web API using ASP.NET Core. Look into RESTful design to also get an idea on how to best setup these end points.
Good luck!
The current route configuration on your controller and on your action will result in duplicated section in your route. Specifically, the route the action will be associated with will be "api/RecLoadPrime/RecLoadPrime/insertRecLoadData/{RecStartDate}/{RecEndDate}".
Consider removing the RecLoadPrim/ prefix from your action route attribute as follows:
[Route("insertRecLoadData/{RecStartDate}/{RecEndDate}")]

How can I safely handle POST parameters in an HTTP Handler using C#?

I'm working on an ASP.Net C# application (my first!) that contains an HTTP Handler within it. My application works with several parameters that are passed in via the URL. My question(s) is as follows:
My applications entry point is via the HTTP Handler. When I enter my ProcessRequest method, I am assigning the values of the URL parameters to variables so that I may do something with the data.
Question: Is this safe, even if I am not setting the value to anything when I call the URL?
In my example: I call host/handler1.ashx instead of host/handler1.ashx?something=foo
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string something = context.Request["something"];
context.Response.Write("Hello World: " + something);
}
When calling the above method using the plain URL with no parameters, it executes just fine, but the string something is just blank/null.
Additional questions:
What happens to the variable something in the case that I do not explicitly initialize it via the URL? I understand that it is null, but can this lead to problems?
Is it dangerous or not safe to call the plain URL (i.e. should I always call it with parameter values specified)?
What is the best way to call a "clean" ashx URL to start the application but not risk problems?
The application will do a series of subsequent GET redirects as it accumulates values and passes them back to the app via the query string.
Should I do a POST or GET upon initial call of the application?
Sorry for asking the same question multiple ways, but I'm a bit confused on the topic and this is my first time writing an app like this. Any patience and advice you could provide on how to safely handle and initialize parameters is greatly appreciated!
There is nothing wrong with omitting parameters to an endpoint. As the developer you are in charge of enforcing what the client is allowed send to you. If you expect a parameter and it's missing, throw an error (e.g. HttpException).
If you are creating or updating data (i.e. inserting or updating records in a database) the best method would be a POST or PUT.
Edit - Here is an example of how you can handle the input:
public void ProcessRequest(HttpContext context) {
//Maybe you require a value?
if (string.IsNullOrEmpty(context.Request["something"])) {
throw new HttpException(400, "You need to send a value!");
}
//Maybe you require a certain value?
if (context.Request["something"] != "beerIsGood") {
throw new HttpException(400, "You need to send the right value!");
}
}
You can't. The Internet is dangerous.

create cookie in web method

i have a web method that check user in data base via a jquery-ajax method i wanna if client exists in db i create a cookie in client side with user name but i know that response is not available in staticmethod .how can i create a cookie in a method that call with jquery ajax and must be static. its my code that does not work cuz response is not accesible
if (olduser.Trim() == username.Trim() && password.Trim()==oldpass.Trim())
{ retval =olduser;
HttpContext context = HttpContext.Current;
context.Session[retval.ToString()] = retval.ToString();
HttpCookie cook = new HttpCookie("userath");
cook["submituser"] = "undifiend";
Response.Cookies.Add(cook);
}
You can access the Response object in the same way you are accessing the Session object from the current HtppContext.
Your code should end like this:
context.Response.Cookies.Add(cook);
You could pass the HttpContext into the static method from the Web Method that the AJax call first enters.
EDIT: or, don't use a static method. Either way, the HttpContext will be available from the instanced Web Method that the Ajax call sees via [WebMethod] annotation.
First make an ajax call. You can read this great tutorial 5 Ways to Make Ajax Calls with jQuery
Second get the server respond. For example if the callback was '1', it means you should set the cookie and if it was '0' you should not.
At Last you can easily set the cookie using this jquery plugin: jquery.cookie.

MVC Routes - How to get a URL?

In my current project we have a notification system. When an oject is added to another objects collection, an email is sent to those who are subscibed to the parent object. This happens on the object layer and not in the View or Controller.
Here's the problem:
Although we can say who created what with what information in the email, we cannot embed links to those objects in the email because in the object layer there is no access to a UrlHelper. To construct a UrlHelper you need a RequestContext, which again does not exist on the object layer.
Question:
I want to make a helper class to create the url's for me. How can I create an object that will generate these urls without a request context? Is it possible?
The problem is compounded by the fact that you don't want a relative URL in an email, you want an absolute email so you need to hard-code the domain too because there is no request to grab it from.
Another factor is that emails can outlive the current site structure by months or years so you need a kind of permalink, and thus a way to associate multiple Urls with a single action (additional routes). This latter issue is also a factor in SEO where you don't want to leave any page behind.
For now a static method on your controller UrlToActionX(params) sitting next to the method ActionX seems like the simplest workaround. All it does is the appropriate string.Format(...) on the id's of the strongly-typed parameters to generate the permanent Url. Add a static domain on the front, or a domain from the user object (since you know which domain they visit when they come to your site) and you have your email link.
It's not ideal but at least you now have only one place to maintain the Url generation.
IMHO: When it comes to permanent links to a changing web site sometimes it's better to rely on "configuration over convention". :-)
I'm not aware of a way to do this, you MUST have access to the routes at the very least to make your own helper. Unless your business objects know about the registered routes, you can't get away from doing some hard-coding.
Here is how you might limit the hard-coding of urls though...
Code in a url with all the relevant bits in your object's methods..
class Event
{
public void SendEmail()
{
var url = string.Format("http://myurl.com/r/Event?eventId={0}", EventId);
//send emails...
}
}
Note the /r/Event piece of the url. This would be a map to a RController that would be responsible for taking arbitrary, made-up links and sending a 301 Permanent Redirect and going through the route engine to create a real url using the current routes. This way you are only hard-coding a utility controller url and not to the ever evolving controller actions of your real pages.
class RController : Controller
{
public ActionResult Event(int eventId)
{
Response.StatusCode = (int)HttpStatusCode.MovedPermanently;
Response.RedirectLocation = Url.Action("Details", "Event", new { eventId = eventId });
return null;
}
public ActionResult Register(int eventId)
{
Response.StatusCode = (int)HttpStatusCode.MovedPermanently;
Response.RedirectLocation = Url.Action("Register", "Event", new { eventId = eventId });
return null;
}
}
It just feels a bit better than hard-coding a bunch of different controllers/actions that you might decide to rename later. Think of it as your own little TinyUrl like service.
You could define an interface with a method that takes whatever information is necessary to create a URL (object ids or whatever) and returns a URL. Write an implementation of that interface that uses the UrlHelper to do this work, and then supply this to your object layer (ideally with an IoC container).
You could use:
VirtualPathUtility.ToAbsolute(string.Format("~/r/Event?eventId={0}", id))
to resolve the url. Still not nice though.

Categories

Resources