What is the replacement of FormDataCollection in Asp.Net core? - asp.net-core

I am trying to use FormDataCOllection in Asp.Net core web api project. As per the documentation it is not there in .net core.
How can I still use it? Or What has replaced it?

You can use the Form property of HttpContext.Request which will return an IFormCollection instance.

FormDataCollection is normally type of the information/class/model sent by forms or grid edit or sumbit links. You can simply use the string as input parameter and then using Json, convert it to the class type you've expected.
Here is an example:
public string NewUser(string values)
{
var message = "";
try
{
var newUser = new User_Detail();
JsonConvert.PopulateObject(values, newUser);
db.User_Detail.Add(newUser);
db.SaveChanges();
message = "User cretaed successfully";
}
catch (Exception ex)
{
message = "An error happened in this method.";
}
return JsonConvert.SerializeObject(message);
}
So, PopulateObject converts your input string (values in this example) to the class you've expected, something similar to FormDataCollection you've needed.
Note: JsonConvert is in Newtonsoft.Json namespace

Related

asp net core soap request ws-addressing

I am creating a wcf client on core.
I create a binding.
var binding = new System.ServiceModel.BasicHttpsBinding();
I need to add MessageID, ReplyTo fields to the request for ws-addressing.
How to do it correctly?
I tried to overwrite request - it didn't work.
All examples are mostly on the usual net framework
It seems there is a library microsoft.web.services2, but I do not understand how to use it.
I'm working on the same requirement, I've found the way to modify the header is work with the OperationContextScope and work with OperationContext.Current.OutgoingMessageHeaders and change the properties.
public async Task<getAttorneyResponseStructure> GetAttorneyAsync(GetAttorneyRequestStructure getAttorneyRequestStructure)
{
try
{
using (new OperationContextScope(Client.InnerChannel))
{
//Client Custom Header
getAttorneyRequestStructure.AttorneyHeader = Header;
//Change the properties to ReplyTo/MessageId
OperationContext.Current.OutgoingMessageHeaders.To = new Uri("http://rydwvgsn01.spga.gov.sa/GSBExpress/Legal/MOJAttorneyInquiry/2.0/AttorneyInquiryService.svc");
OperationContext.Current.OutgoingMessageHeaders.Action = "http://tempuri.org/IAttorneyInquiryService/GetAttorney";
return await Client.GetAttorneyAsync(getAttorneyRequestStructure);
}
}
catch (Exception e)
{
throw;
}
}

ASP.NET Core 3.1 "Unsupported handler method return type 'Microsoft.AspNetCore.Mvc.Rendering.SelectList'"

As soon as set the return type of a function as SelectList I get this error:
Unsupported handler method return type 'Microsoft.AspNetCore.Mvc.Rendering.SelectList'
public SelectList OnGetCategories()
{
//whatever
return null;
}
The body of function does not matter.
I even do not use the function, being the function in the code is enough for raising error.
SelectList or Null output does not matter.
This code was working in ASP.NET Core 2.2 without any error and I could call it by jQuery Ajax to retrieve my categories in a proper format.
Similar to what is suggested by #itminus in the comments:
public IActionResult OnGetCategories()
{
return new JsonResult(result);
}

Unable to cast object of type System.Security.Claims.ClaimsPrincipal to type Microsoft.IdentityModel.Claims.IClaimsPrincipal

I am developing one MVC4 application which authenticate corp domain users using ADFS and i have written the code and i am getting the error like below, am i not getting claims ?
System.InvalidCastException: Unable to cast object of type 'System.Security.Claims.ClaimsPrincipal' to type 'Microsoft.IdentityModel.Claims.IClaimsPrincipal'.
public ActionResult Index()
{
try
{
IClaimsPrincipal principal = (IClaimsPrincipal)Thread.CurrentPrincipal;
IClaimsIdentity identity = (IClaimsIdentity)principal.Identity;
if (String.IsNullOrEmpty(identity.Claims[0].Value.Split('#')[0]))
{
ViewData["Message"] = string.Format("You are email is :{0}", identity.Claims[0].Value.Split('#')[0]);
}
else
{
ViewData["Message"] = "You are not getting any claims";
}
}
catch (Exception ex)
{
ViewData["Message"] = "Something wrong.";
}
return View();
}
What you observe is result of mixing .NET 3.5 WIF (Microsoft.IdentityModel) and WIF 4.0 (System.IdentityModel & System.Security).
What I suggest is:
Remove reference to Microsoft.IdentityModel.* assemblies in your project
Add reference to System.IdentityModel & System.IdentityModel.Services assemblies
Fix using statements
Fix references to Microsoft.IdentityModel in your Web.Config
Do a backup copy of your project before doing this, because, if you haven't done this before, you might end up with a lot of error and not working code. But the main idea is that you have to get rid of all and any Microsoft.IdentityModel references and you will be good.
I am able resolved this issue as per astaykov suggestion and i changed the code like below,
using System.Security.Claims;
var identity = User.Identity as ClaimsIdentity;
foreach (var claim in identity.Claims)
{
if (claim.Type.Contains("EmailAddress"))
{
ViewBag.EmailName = claim.Value;
}
}

Passing values in Header

We are consuming an external web service (WCF) in our AX2012 project. We followed the procedure described in the following blog.
We are implementing security by passing the token in the header. However, what i am not sure of is how to do this in AX2012.
the sample code for getting the token is
static void myTestServiceWSDL(Args _args)
{
myServiceWSDL.Proxies.Service.ServiceClient service;
myServiceWSDL.Proxies.Service.LoginData LoginData;
str token;
System.Exception ex;
System.Type type;
try
{
type = CLRInterop::getType('myServiceWSDL.Proxies.Service.ServiceClient');
service = AifUtil::createServiceClient(type);
LoginData = new myServiceWSDL.Proxies.Service.LoginData();
LoginData.set_uName("test");
LoginData.set_pwd("test");
token=service.Login(LoginData);
info(token);
}
catch(Exception::CLRError)
{
ex = CLRInterop::getLastException();
info(CLRInterop::getAnyTypeForObject(ex.ToString()));
}
}
The token comes back fine which confirms the code is working.
Now the question is how to do i set header values for the message.
If it was C# i would have done
using (MemberMasterClient proxy = new MemberMasterClient())
{
using (OperationContextScope scope
= new OperationContextScope(proxy.InnerChannel))
{
// set the message in header
MessageHeader header =
MessageHeader.CreateHeader("SourceApplication",
"urn:spike.WCFHeaderExample:v1",
"WCFClient Application 2");
OperationContext.Current.OutgoingMessageHeaders.Add(header);
Console.WriteLine("Membership Details");
Console.WriteLine("Henry's - {0}", proxy.GetMembership("Henry"));
}
}
}
Could any one let me know how to do the equivalent in X++
One idea which has been on my mind is to write an assembly in C# which can then be called in AX2012. Will give that a go, but the idea is to code this in X++ in AX2012
The only thing you do differently in X++ is creating the proxy using the Aif utility. So basically, your C# example you listed, the only difference would be the proxy = new MemberMasterClient() which goes through AIF. All the other code you can take into X++ as-is (except for the "using"). You just need to have the right assemblies reference in the AOT, and use the full namespace in the code.
Alternatively, as you mentioned, you can just code it all in C# and call that from AX :-)

Creating an SPListItem in a WCF service deployed to SharePoint

i have the following method in a WCF service, that has been deployed to SharePoint using Shail Malik's guide:
[OperationContract]
public string AddItem(string itemTitle, Guid? idOfListToUse)
{
using (var portal = new SPSite(SPContext.Current.Site.Url, SPContext.Current.Site.SystemAccount.UserToken))
{
using (var web = portal.OpenWeb())
{
Guid listId;
web.AllowUnsafeUpdates = true;
if (idOfListToUse != null && idOfListToUse.Value != new Guid())
{
listId = idOfListToUse.Value;
}
else
{
try
{
listId = new Guid(web.Properties[PropertyBagKeys.TagsList]);
}
catch (Exception ex)
{
throw new MyException("No List Id for the tag list (default list) has been found!", ex);
}
}
var list = web.Lists[listId];
string title = "";
SPSecurity.RunWithElevatedPrivileges(delegate{
var newItem = list.Items.Add();
newItem["Title"] = itemTitle;
newItem.Update();
title = newItem.Title;
});
web.AllowUnsafeUpdates = false;
return title;
}
}
}
When the method gets called from Javascript (using Rick Strahl's excellent ServiceProxy.js) it fails and it does so on newItem.Update() because of ValidateFormDigest().
Here's the kicker though, when I step through the code it works! No exceptions at all!
Ok, found the answer (there's 2 even :-D)
First, the dirty one:
Set FormDigestValidatedProperty in the context:
HttpContext.Current.Items["FormDigestValidated"] = true;
Second, the slightly less dirty version (basically leaving the way open for XSS attacks, but this is an intranet anyway)
The answer
I don't think you can access 'list' as it was created outside the elevated code block.
http://blogs.pointbridge.com/Blogs/herzog_daniel/Pages/Post.aspx?_ID=8
I'm guessing when you are stepping though the entire process is in admin mode so all are elevated.
Colin, it's a really bad idea to try to access HttpContext (likewise SPContext) inside a WCF service. See here: MSDN: WCF Services and ASP.NET
From the article:
HttpContext: Current is always null
when accessed from within a WCF
service.
It's likely this is the cause of your problem.
EDIT: I notice that you're trying to use SPContext to get the url of the site collection. I didn't find a good solution to this either so I just send the url of the target site collection as a parameter to the service call. Not the most optimal solution but I couldn't think of a better way. Also, if you need to check authentication/identities, etc use ServiceSecurityContext.Current.