Get access to HttpActionContext outside of my Web API 2 Controller - c#

Inside my Controller class I can do this:
var userId = this.ActionContext.RequestContext.Principal.Identity.Name;
But I have a soap header that I want to pass this value into. The behavior that uses the soap header is setup using my dependency injection. So while it is created for each call, it is not created in the Controller.
So I am wondering, is there a way to get access to Web API 2's HttpActionContext outside the controller. Ideally I would want something like this:\
HttpActionContext.CurrentInstance.RequestContext.Principal.Identity.Name;
But of course CurrentInstance does not exist as a static member of HttpActionContext.
But is there some other way to get this without the Controller?

You can access identity name using following
System.Web.HttpContext.Current.User.Identity.Name

Related

Url.Action does not exist in the current context

I am using ASP.Net Core.
I have a function I am trying to move to a separate class to be called by multiple controllers.
This function woud build a pdf with links inside it.
For the links, I use:
string urlMeeting = Url.Action("Detail", "Event", new { id = "meeting-" + MeetingID });
It works perfectly fine in my controller but when I move the function from the controller into a separate class in the same project, I keep getting "The name Url does not exist in the current context".
I tried adding using Microsoft.AspNetCore.Mvc; but same error.
What did I miss? Why doesn't it complain in my controller and does in my external class?
Because your custom controller does inherit from the controller class.
This means u Have access to the Url property in the base class.
But when u move the code to a seperate class u dont have access to that property.
A solution to this is to parametrize the function that you are calling with the Url.

ASP.NET Core UrlHelper and how it works

I'm rather new to ASP.NET Core, and right now I am trying to get a grasp on how UrlHelper works in general.
In my controller, I want to create an absolute URL to another action in the same controller, e.g. http://localhost:PORT/api/controller/action. The question is now, how do I do it?
I have tried with the following:
var urlHelper = new UrlHelper(new ActionContext());
var url = urlHelper.Action("ACTION", "CONTROLLER");
Furthermore, what are those different contexts like ActionContext?
You really shouldn’t create a UrlHelper yourself. It’s likely that whatever context you are currently in, there is already an IUrlHelper instance available:
ControllerBase.Url inside of controllers.
PageModel.Url inside a Razor view.
ViewComponent.Url inside a view component.
So chances are, that you can just access this.Url to get an URL helper.
If you find yourself in a situation where that does not exist, for example when implementing your own service, then you can always inject a IUrlHelperFactory together with the IActionContextAccessor to first retrieve the current action context and then create an URL helper for it.
As for what that ActionContext is, it is basically an object that contains various values that identify the current MVC action context in which the current request is being handled. So it contains information about the actual request, the resolved controller and action, or the model state about the bound model object. It is basically an extension to the HttpContext, also containing MVC-specific information.
If you are running ASP.NET Core 2.2 or later, you can also use the LinkGenerator instead of the IUrlHelper inside your services which gives you an easier way to generate URLs compared to having to construct the helper through the IUrlHelperFactory.

skip all Umbraco magic for single method

I was just assigned to implement one functionality in project that uses Umbraco. My job is to basically generate specific XML and return it to user. However i cannot get it to work, because when i create new controller (i've tried creating
Controller, RenderMvcController and SurfaceController
) and method in it (also if i just create new method in existing controller), i get error 404 after typing url into browser. Example: I create TestController and method Index in it. I've tried combinations where TestController was derived from RenderMvcController or SurfaceController or just Controller. After compiling, etc. when i run
http://my_address/Test
or
http://my_address/Test/Index
i get 404 error from umbraco. I looked at another pages in umbraco that were already in project and they all are also configured somehow in umbraco web panel:
http://my_address/umbraco
I aslo tried adding new methods to existings controllers, but no luck (again 404 errors). I've never worked with umbraco and i don't know how to configure it. I just want to know if there is any way to create method which will be accessible at:
http://my_address/MyMethod
or
http://my_address/MyController/MyMethod
and would return just exactly what i will program it to (without any Views, Partial Views, etc. - i can set Headers and ContentType manually and my content is pure text) in an existing Umbraco project without having to deal with umbraco admin panel?
Thanks for any help :)
//Edit
My mind is officially blown... My response is culture dependent (i mean i pull different data from db depending on country), but it's not as simple as
CurrentCulture.CultureInfo
Umbraco is configured to return different culture based on domain extension (Germany for .de, Great Britain for .co.uk, and Dennmark for .dk - it's just a manual configuration in umbraco admin panel assigning different culture info and views to different hostnames). Regular controllers get this modified culture from
RenderModel.CurrentCulture
passed as argument to controller's method. Is there a way to create umbraco controller/method/anthing that will not have layout/model assigned to it (so i can display pure XML data i receive from external service) and still have access to umbraco's RenderModel's culture? What i am trying to create is if user types url:
http://my_address.de/myController/myMethod
my controller will get current culture, call external service passing culture as parameter and display received data without wrapping it in any views. Example:
public class myController : SomeBaseUmbracoControllerOrsomething
{
public string/XmlDocument/ActionResult myMethod(RenderModel model)
{
int countryId = myFunctionToTranslateCultureToCountryId(model.CurrentCulture);
return MethodThatCallsExternalServiceAndReturnsXml(countryId);
}
}
Sorry for confusion, but i've learned about this whole mess with countries just now...
You don't want to use
controller, because this is not picked up by umbraco routing process
you don't want to use RenderMvcController, because this is overkill
you don't want to use Surfacecontroller because you are not using a Child action or form.
What you need is a UmbracoApiController (http://our.umbraco.org/documentation/Reference/WebApi/) or is your umbraco version is PRE 6.1 then use /Base extention (http://our.umbraco.org/documentation/Reference/Api/Base/Index)
Or if you really want to skip ALL umbraco magic for a certain route, add the path to the web.config/AppSettings/umbracoReservedUrls.

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

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.

How do I access Request.cookies in an ASP.NET MVC controller?

I'm trying to get a user ID stored in cookies via a common Controller file, which I can access throughout the site.
I have created FunctionsController as a controller, with content as follows:
public static int loggedinUser()
{
return Convert.ToInt32( request.Cookies["userid"].Value);
}
I am unable to request any cookie items even if I tried with:
HttpRequestBase request = controllerContext.HttpContext.Request;
I don't have a problem accessing cookies in ASP.NET MVC using a standard access statement such as:
Request.Cookies["someCookie"]
Your sample had a lower-cased "r" in "request.Cookies". Could that be your problem?
Remove the static part of your method declaration and then use Request.Cookies["userId"]

Categories

Resources