Web.Api Attribute Not Showing on Controller - c#

I am trying to use Mike Wallace's "RequireHttps" attribute to force certain controllers to require SSL or not.
I have the code below, and it builds fine. But when I actually go to add the attribute to the controller, it fails.
I have other custom attributes that appear, and I have another that doesn't. So it might be a project issue, though I tried a new project and it still failed. The code is in the app_code folder.
using System;
using System.Net.Http;
using System.Web.Http.Filters;
using System.Web.Http.Controllers;
namespace WebAPIService
{
public class RequireHttpsAttribute : AuthorizationFilterAttribute
{
public RequireHttpsAttribute();
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "HTTPS Required"
};
}
else
{
base.OnAuthorization(actionContext);
}
}
}
}
Any suggestions are welcomed. Thanks.
EDIT:
The error I get on the API Controller is:
The type or namespace name 'RequireHttpsAttribute' could not be found (are you missing a using directive or an assembly reference?)

You can just put your RequireHttpsAttribute.cs file in a different folder than App_Code, which is a special ASP.NET folder. Your namespace import should function correctly, then. If your project is a website project, converting it to a web app might also solve the problem.
If you want to learn more about the issue, I recommend you take a look at Type or namespace could not be found from App_code folder.

Related

C# Response.Write Error from scaffolded "dotnet new mvc"

I'm familiar with PHP and JS, as well as MVC methodology, but I'm completely new to C# and have spent time looking for the documentation on this specific error.
I used dotnet new mvc to create a working app on port 5000. Also note, I am working in the Controller, not the model or view:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ExelonPrime.Models;
namespace OptimusPrime.Controllers{
public class ApiController : Controller
{
public void Help_Pdf()
{
Response.Write("test");
}
}
}
And the error I get (when trying to compile) is:
error CS1061: 'HttpResponse' does not contain a definition for 'Write' and no accessible extension method 'Write' accepting a first argument of type 'HttpResponse' could be found (are you missing a using directive or an assembly reference?)
If I'm missing a using directive, which one is it? I tried System.Web and that didn't work. How do I make this work?
I would recommend following through microsofts tutorial on using asp.net core.
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/?view=aspnetcore-2.2
As far as this specific instance, rather than using Response.Write, I would do this
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SampleWeb.Models;
namespace SampleWeb.Controllers
{
public class ApiController : Controller
{
[HttpGet]
public ActionResult<string> Help_Pdf()
{
return "test";
}
}
}
This specific sample might be helpful.
With this class, the url https://localhost:5001/api/Help_Pdf returns "test"
In ASPNET Core, when writing an API, it's more common to return an object, or POCO in stead of directly writing to the response stream (although it indeed is possible)
try changing your
public void Help_Pdf()
{
Response.Write("test");
}
to
[HttpGet()]
public IActionResult Help_Pdf()
{
return Ok();
}
this will return an 204 (no content), you can pass data however, to the OK function, to add a body to the response object.
If your trying to write directly to the response stream like that, you can do this:
public async Task Help_Pdf()
{
await Response.WriteAsync("Test");
}
However, I'd recommend not doing this in your actual app, the method should return an IActionResult. IMO it's not good practice to write directly to the stream in your controller methods (not very test friendly).

Error: The type or namespace name 'ApplicationUser' could not be found in Visual Studio 2013

I am following the "RESTful WCF Service" tutorial. But when I built my application I get this error:
The type or namespace name 'ApplicationUser' could not be found (are you missing a using directive or an assembly reference?)
c:\users\basma\documents\visual studio 2013\Projects\OnlineStore2\OnlineStore2_Client\App_Start\IdentityConfig.cs
I've searched and many answers where talking about "Microsoft ASP.NET Identity.owin" but I added this reference but still get this error
Create a class called ApplicationUser that derives from IdentityUser. It doesn't need to have any properties or methods, but you can freely extend it with any information you want to store about each user you have on the system (think name, addresses, etc.).
public class ApplicationUser : IdentityUser
{
public virtual string Email { get; set; } // example, not necessary
}
Linking the namespace
using YourProjectName.Models;
worked for me. In the post's case, "YourProjectName" is "OnlineStore2"

Umbraco Custom Controllers, the basics

I am getting this error "the type or namespace name 'Umbraco' could not be found"
I am using it in a custom controller HomeController.cs which lives in root/controllers/HomeController.cs.
But I can not seem to find any Umbraco namespaces.
using Umbraco.Web;
using Umbraco.Web.Models;
namespace umbraco.umbraco.Controllers
{
public partial class HomeController : Umbraco.Web.Mvc.RenderMvcController
{
}
}
any help with the basic is greatly appreciated
Regards
Can you try renaming your namespace?
umbraco.umbraco.Controllers
to
YourProject.Controllers

LightInject SignalR missing .RegisterHubs method

I just started using LightInject for my MVC project and it's working just fine.
But i wanted to use it for my SignalR hubs too. So i followed the instructions at http://www.lightinject.net/#signalr. However i cannot see the method ServiceContainer.RegisterHubs anywhere. I have installed the LightInject, LightInject.Mvc and LightInject.SignalR dll's.
using log4net.Config;
using LightInject;
using Microsoft.Owin;
using Owin;
using MvcProject;
using MvcProject.ApplicationServices.Interfaces.EventSignups;
[assembly: XmlConfigurator(ConfigFile = "Web.config", Watch = true)]
[assembly: OwinStartup(typeof (Startup))]
namespace MvcProject
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
//ConfigureAuth(app);
var container = new ServiceContainer();
container.Register<IEventSignupService>();
container.Register<IViewModelRetrieverEventCommentService>();
container.Register<IViewModelRetrieverEventService>();
container.RegisterHubs(); //cannot see method
app.MapSignalR(container.EnableSignalR());
}
}
}
Anyone knows what i'm doing wrong?
Unfortunately this is just bad documentation. The method does not exist and never existed. You have to register each and every hub manually within your LightInject Container.
Also, be aware of issues I've encountered by changing the DependencyResolver within SignalR for LightInject.
PS: I know my answer is late but still tought it could be useful for people searching for the same issue.

Where is Request.CreateErrorResponse?

I saw it in this blog post, but that doesn't actually say how to "enable" it. And it seems that by default it isn't enabled.
I know it's an extension method, as defined here: http://msdn.microsoft.com/en-us/library/hh835786(v=vs.108).aspx but how do I get access to it? If I type Request.CreateErrorResponse then the compiler doesn't recognize it.
I'm already using System.Net.Http.
I've noticed this in release version as well. And if you don't have the right using statement, it'll error. You need :
using System.Net.Http;
even if you already have this:
using System.Web.Http.Controllers;
Are you still using pre-release or release version? There were a number of extensions that did not appear until just before the release and did not exist in earlier versions of the webapi release. I am unsure if this was one of them, but it may be what is causing your problem.
Request is the public property of the ApiController class and should be available to you in any API actions in that controller.
public abstract class ApiController
{
...
public HttpRequestMessage Request { get; set; }
}
Here is a small code sample that works for me:
using System.Net;
using System.Net.Http;
using System.Web.Http;
public class MyFirstApiController : ApiController
{
// GET
public HttpResponseMessage Get(int id)
{
return Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Some message here");
}
}
Interestingly enough, if I take away using System.Net.Http; statement, Request no longer has a CreateErrorResponse() method.
Although important points have been answered.
One more dumbest possibility is that you might have chosen wrong type of controller.
Make sure you have created an Web API controller, incase of MVC controller you cannot have
Request.CreateErrorResponse()
Just another possibility where you may find this issue.
In .net core, add Microsoft.AspNetCore.Mvc.WebApiCompatShim.dll .
https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httprequestmessageextensions.createerrorresponse?view=aspnetcore-2.0
Use System.Web.Http assembly.
source: CreateErrorResponse Method
you can use from that In block Try-Catch.
[HttpGet]
public HttpResponseMessage DownloadVideo(Guid id, string title)
{
try
{
//Your Code at the end return result
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex.Message);
}
}
Inject and instance of the HttpRequestMessage in your controller constructor or method:
Task<ActionResult<GetOneShopDtoResponse>> GetOne(HttpRequestMessage request,int shopId) {
return request.CreateErrorResponse(.....)
}
My best guess is that it is the third assembly, that you haven't referenced, that is the problem.
Unfortunately I don't have access to my computer, browsing on my phone, so I can't track down the file for you. According to the docs it should be in System.Web.Http.SelfHost.dll, so I guess you could just search for that file to locate it.

Categories

Resources